import { Funnel } from "@ant-design/charts"
import { ProductCountQuery, ProductCountReport, TotalProductCounts } from "@mallfoundry/report"
import { Card } from "antd"
import * as React from "react"
import { useEffect, useState } from "react"
import classes from "./product-conversion-rate.module.scss"

interface ProductCountFunnelProps {
  storeId: string
}

function ProductCountFunnel(props: ProductCountFunnelProps) {
  const { storeId } = props
  const [totalProductCounts, setTotalProductCounts] = useState(new TotalProductCounts())
  const asyncFetch = () => {
    ProductCountReport
      .queryTotalProductCounts(new ProductCountQuery().toBuilder().storeId(storeId).build())
      .then(setTotalProductCounts)
  }
  useEffect(asyncFetch, [storeId])

  const { viewCount, addedCount, placedCount, paidCount, completedCount } = totalProductCounts

  const data = [
    {
      action: "浏览网站",
      count: viewCount,
    },
    {
      action: "放入购物车",
      count: addedCount,
    },
    {
      action: "生成订单",
      count: placedCount,
    },
    {
      action: "支付",
      count: paidCount,
    },
    {
      action: "成交",
      count: completedCount,
    },
  ]
  const config = {
    padding: [0, 0, 0, 0],
    height: 238,
    forceFit: true,
    data: data,
    xField: "action",
    yField: "count",
    legend: {
      visible: false,
    },
    percentage: {
      visible: false,
    },
  }
  return <Funnel {...config} />
}

interface ProductConversionRateProps {
  storeId: string
}

export default function ProductConversionRate(props: ProductConversionRateProps) {
  const { storeId } = props
  return (
    <Card title="商品转化率" size="small" className={classes.ProductConversionRate}>
      <ProductCountFunnel storeId={storeId}/>
    </Card>
  )
}
